/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.QuotationDAOInterface;
import com.wii.elpro.dao.hb.QuotationDAOImpl;
import com.wii.elpro.entity.Quotation;
import com.wii.elpro.entity.QuotationItem;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author hp02
 */
public class QuotationGetQuotationDetailAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        String forward;
        QuotationDAOInterface dao = new QuotationDAOImpl();
        HttpSession sess = request.getSession(true);
        ActionMessages messages;
//        AT THIS LINE QUOTATION's ID STORED IN SESSION
        sess.setAttribute("idQuotation", request.getParameter("id"));
        List<QuotationItem> items = null;
        try {
            if(sess.getAttribute("listItem")!=null) {
                items = (List<QuotationItem>) sess.getAttribute("listItem");
            } else {
                items = null;
            }
            sess.setAttribute("listItem", items);
            Quotation quotation = dao.getQuotation(Long.parseLong(request.getParameter("id")));
            request.setAttribute("quotation", quotation);
            double total = 0;
            for(QuotationItem i:quotation.getItems()) {
                    total = (i.getPriceList()-(i.getPriceList()*i.getDisc())/100)+total;
            }
            request.setAttribute("total", total);
            
            double grandTotal = 0;
            for(QuotationItem item: quotation.getItems()) {
                    grandTotal = (item.getPriceList()-item.getPriceList()*(item.getDisc()/100))+grandTotal;
            }
            grandTotal = grandTotal-(grandTotal*quotation.getVat())/100;
            request.setAttribute("grandTotal", grandTotal);
            forward = "success";
        } catch (Exception ex) {
            messages = new ActionMessages();
            messages.add("message", new ActionMessage("customMessage", "Application is fail to retrieve data. Please contact my developer."));
            saveMessages(sess, messages);
            ex.printStackTrace();
            forward = "fail";
        }
        return mapping.findForward(forward);
    }
}
